import jwt from "jsonwebtoken"
const secret = "OMG2.0TEMP" // 密钥

/**
 * 颁发签名
 * @param {*} resp response 
 * @param {*} maxAge 过期时间
 * @param {*} info jwt 信息
 */
export function publish(resp: any, maxAge: any, info = {}) {

  const token = jwt.sign(info, secret, {
    expiresIn: maxAge
  })
  // 添加到cookie
  // resp.cookie(cookieKey, token, {
  //   maxAge: maxAge * 1000,
  //   path: "/"
  // })
  // 添加其他传输
  resp.header("authorization", "Bearer " + token)
}

// 解析签名
export function decoded(req: any) {

  // let a = req.cookie

  // let token = req.cookies[cookieKey]

  let token = req.headers.authorization;
  // if (!token) {
  //   // 没有cookie
  //   token = req.headers.authorization;
  if (!token) {
    // 没有 authorization
    return null;
  }
  // }

  // authorization:bearer xafasfsafdsfs(token)
  token = token.split(" ");
  token = token.length === 1 ? token[0] : token[1];

  // 有token 验证是否正确
  try {
    // tslint:disable-next-line: no-shadowed-variable
    const decoded = jwt.verify(token, secret);
    return decoded;
  } catch (err) {
    return null;
  }
}
